package com.epam.weblibrary.controllers;

import com.epam.weblibrary.entities.book.Book;
import com.epam.weblibrary.service.book.BookService;
import com.epam.weblibrary.service.book.BookServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;

/**
 * Created by DruidKuma on 9/8/14.
 */
@Controller
@SessionAttributes({"cart"})
public class BookController {

    @Autowired
    private BookService bookService;

    @RequestMapping(value = "/books/{pageNumber}", method = RequestMethod.GET)
    public String getPagedBookList(@PathVariable Integer pageNumber, Model model) {
        if(!model.containsAttribute("cart")) {
            model.addAttribute("cart", new ArrayList<Book>());
        }

        Page<Book> page = bookService.getBookPage(pageNumber);

        int current = page.getNumber() + 1;
        int begin = Math.max(1, current - 3);
        int end = Math.min(begin + 3, page.getTotalPages());

        model.addAttribute("books", page);
        model.addAttribute("beginIndex", begin);
        model.addAttribute("endIndex", end);
        model.addAttribute("currentIndex", current);
        model.addAttribute("contents", page.getContent());

        return "book/list";
    }

    @RequestMapping(value = "/book", method = RequestMethod.GET)
    public String getViewContact(@RequestParam Long id, Model model) {
        model.addAttribute("book", bookService.find(id));
        return "book/view";
    }

    @RequestMapping("/book-cover/{id}")
    public ResponseEntity<byte[]> getBookCover(@PathVariable("id") Long id) throws IOException {

        final HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_JPEG);

        Book book = bookService.find(id);
        return new ResponseEntity<byte[]>(book.getCover(), headers, HttpStatus.CREATED);
    }
}
